home *** CD-ROM | disk | FTP | other *** search
- Path: news.primenet.com!jstern
- From: jstern@primenet.com (Josh Stern)
- Newsgroups: comp.lang.c++
- Subject: Re: How to initialize array of objects using non-void constructor?
- Date: 3 Apr 1996 21:57:02 -0700
- Organization: Primenet Services for the Internet
- Sender: root@primenet.com
- Message-ID: <4jvkqu$8kp@nnrp1.news.primenet.com>
- References: <4jbuo5$mcb@newshost.lanl.gov> <315C8F65.78D5@aai.arco.com> <315F5E13.799D1B33@alcyone.com> <DpAoG2.nCn@undergrad.math.uwaterloo.ca>
- X-Posted-By: jstern@usr1.primenet.com
-
- Steve Kettle <sckettle@undergrad.math.uwaterloo.ca> wrote:
- >Erik Max Francis <max@alcyone.com> wrote:
- >>Brian Leach wrote:
- >>> Liang Lu wrote:
-
- >>> Sorry Liang, it is not possible. The language does not allow for
- >>> non-default
- >>> constructors for arrays of objects.
-
- The language basically provides the placement form
- of operator new for this purpose (see below).
-
- >>Nonsense; see Ellis & Stroustrup, 12.6.1. Using non-default constructors for
- >>initializing an array is much the same as one would expect (using the example
- >>above):
- >>
- >> Table object[3] = { object(1), object(1), object(2) };
-
- >But you can't for an array on the heap.
-
- Yes you can, it goes like this:
-
- #include <new.h> // for placement new
-
- Table* tptr = malloc(sizeof(Table)*num_tables);
- if (!tptr) exit(1); // malloc failed
- for (int i=0; i < num_tables; i++)
- new (tptr++) Table(val); // example for single arg constructor
- // arbitrary number of args possible
-
- There is also a do-nothing placement form of delete
- that simply calls the destructor for the objects.
- For convenience, check out the templates Construct
- and Destroy in the file defalloc.h of the HP implementation
- of STL.
-
-
- - Josh
-
-
-
- --
- -------------------------------------------------------------------------------
- jstern
- jstern@primenet.com
- -------------------------------------------------------------------------------
-